package com.zyh.dao.impl;

import com.zyh.dao.FollowDao;

import com.zyh.dao.UserDao;
import com.zyh.pojo.User;
import com.zyh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Repository
public class FollowDaoImpl implements FollowDao {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean judgeFollow(Integer uidA, Integer uidB) {
        return redisTemplate.opsForZSet().rank("user:"+uidB+":followers",uidA)==null?false:true;
    }

    @Override
    public void follow(Integer followerId, Integer beFollowerId) {
        redisTemplate.opsForZSet().add("user:"+beFollowerId+":followers",followerId,new Date().getTime());
        redisTemplate.opsForZSet().add("user:"+followerId+":following",beFollowerId,new Date().getTime());

    }

    @Override
    public void unfollow(Integer follower, Integer befollower) {
        redisTemplate.opsForZSet().remove("user:"+befollower+":followers",follower);
        redisTemplate.opsForZSet().remove("user:"+follower+":following",befollower);
    }

    @Override
    public List<User> followers(Integer uid) {
        Set<Object> range = redisTemplate.opsForZSet().range("user:"+uid+":followers", 0, -1);
        List<User> users=new ArrayList<>();
        for(Object id:range){
            users.add(userService.findById((Integer) id));
        }
        return users;
    }

    @Override
    public List<User> followings(Integer uid) {
        Set<Object> range = redisTemplate.opsForZSet().range("user:"+uid+":following", 0, -1);
        List<User> users=new ArrayList<>();
        for(Object id:range){
            users.add(userService.findById((Integer) id));
        }
        return users;
    }
}
